<script>
  import { Crepe } from "@milkdown/crepe";
  import { editorViewCtx, parserCtx, editorViewOptionsCtx } from "@milkdown/kit/core";
  import { listener, listenerCtx } from "@milkdown/kit/plugin/listener";
  import { Slice } from "@milkdown/kit/prose/model";
  import { Selection } from "@milkdown/kit/prose/state";
  import { getMarkdown, insert } from "@milkdown/kit/utils";

  import throttle from "lodash/throttle";
  import { onMount, onDestroy } from "svelte";
  import { eclipse } from "@uiw/codemirror-theme-eclipse";
  import { markdown, crepeAPI } from "./stores";
  import { Editor, rootCtx, defaultValueCtx } from "@milkdown/kit/core";
  import { commonmark } from "@milkdown/kit/preset/commonmark";
  import { nord } from "@milkdown/theme-nord";
  import { createCopyUtils } from "./copyUtils.js";
  import { 
    wordCountPlugin, 
    highlightPlugin, 
    autoSavePlugin, 
    emojiPlugin,
    customCommandsPlugin 
  } from "./customPlugins.js";
  import { aiRewritePlugin, AiRewriteService } from "./aiRewritePlugin.js";

  // 导入样式文件
  // import "@milkdown/theme-nord/style.css";
  import "@milkdown/crepe/theme/common/style.css";
  import "@milkdown/crepe/theme/frame.css";

  export let onChange = () => {};
  export let disabled = false; // 新增禁用状态属性
  
  let crepeRef = null;
  let divRef;
  let loading = false;

  let darkMode = false;
  let content = "# Hello Milkdown!\n\nStart writing...";
  $: content = $markdown;

  const toast = (message, type) => {
    console.log(`${type}: ${message}`);
  };

  const encode = (content) => {
    return btoa(content);
  };

  // 创建复制工具实例
  const copyTool = createCopyUtils(toast);

  export const setCrepeAPI = (apiState) => {
    crepeAPI.set(apiState);
  };

  // 字数统计状态
  let wordCount = { words: 0, characters: 0 };
  
  // 高亮关键词
  export let highlightKeywords = ['重要', 'TODO', 'FIXME', 'NOTE'];
  
  // 自动保存回调
  const handleAutoSave = (content) => {
    console.log('Auto saving content...', content.substring(0, 50) + '...');
    // 这里可以调用实际的保存 API
  };

  // AI 改写服务
  const aiService = new AiRewriteService({
    // apiUrl: 'https://your-ai-api.com/rewrite',
    // apiKey: 'your-api-key'
  });

  onMount(async () => {
    if (!divRef || loading) return;

    loading = true;

    try {
      const crepe = new Crepe({
        root: divRef,
        defaultValue: content,
        features: {
          [Crepe.Feature.Toolbar]: false,
         // [Crepe.Feature.BlockEdit]: false
        },
        [Crepe.Feature.Toolbar]: {
          
          buildToolbar: (builder) => {
            console.log("Building custom toolbar");
            // Custom toolbar building logic
          },
        },
        featureConfigs: {
          [Crepe.Feature.CodeMirror]: {
            theme: darkMode ? undefined : eclipse,
            searchPlaceholder: "搜索代码...",
          },
          [Crepe.Feature.Placeholder]: {
            text: "",
          },
          [Crepe.Feature.LinkTooltip]: {
            onCopyLink: () => {
              toast("Link copied", "success");
            },
            inputPlaceholder: "输入链接地址",
          },
          [Crepe.Feature.BlockEdit]: {
            textGroup: {
              label: "文本",
              text: { label: "段落" },
              h1: { label: "一级标题" },
              h2: { label: "二级标题" },
              h3: { label: "三级标题" },
              h4: { label: "四级标题" },
              h5: { label: "五级标题" },
              h6: { label: "六级标题" },
              quote: { label: "引用" },
              divider: { label: "分割线" },
            },
            listGroup: {
              label: "列表",
              bulletList: { label: "无序列表" },
              orderedList: { label: "有序列表" },
              taskList: { label: "任务列表" },
            },
            advancedGroup: {
              label: "高级",
              image: { label: "图片" },
              codeBlock: { label: "代码块" },
              table: { label: "表格" },
              math: { label: "数学公式" },
            },
          },
        },
      });

      // 配置编辑器可编辑状态
      crepe.editor.config((ctx) => {
        ctx.update(editorViewOptionsCtx, (prev) => ({
          ...prev,
          editable: () => !disabled,
        }));
      });

      // 添加自定义插件
      await crepe.editor
        .use(wordCountPlugin)
       //  .use(highlightPlugin(highlightKeywords))
        .use(autoSavePlugin(handleAutoSave, 30000)) // 30秒自动保存
        .use(emojiPlugin)
        .use(customCommandsPlugin)
       //  .use(aiRewritePlugin(aiService)) // 添加 AI 改写插件
        .create();

      crepeRef = crepe;
      loading = false;

      const handleChange = throttle(() => {
        if (crepeRef) {
          const markdownContent = crepeRef.getMarkdown();
          markdown.set(markdownContent);
          onChange(markdownContent);
        }
      }, 200);

      const observer = new MutationObserver(handleChange);
      observer.observe(divRef, {
        childList: true,
        subtree: true,
        characterData: true,
      });

      setTimeout(() => {
        setCrepeAPI({
          loaded: true,
          onShare: () => {
            const content = crepe.editor.action(getMarkdown());
            const base64 = encode(content);
            const url = new URL(location.href);
            url.searchParams.set("text", base64);
            navigator.clipboard.writeText(url.toString()).then(() => {
              toast("Share link copied.", "success");
            });
            window.history.pushState({}, "", url.toString());
          },
          update: (markdown) => {
            const crepe = crepeRef;
            if (!crepe) return;
            if (crepe.getMarkdown() === markdown) return;
            crepe.editor.action((ctx) => {
              const view = ctx.get(editorViewCtx);
              const parser = ctx.get(parserCtx);
              const doc = parser(markdown);
              if (!doc) return;
              const state = view.state;
              const selection = state.selection;
              const { from } = selection;
              let tr = state.tr;
              tr = tr.replace(
                0,
                state.doc.content.size,
                new Slice(doc.content, 0, 0)
              );
              const docSize = doc.content.size;
              const safeFrom = Math.min(from, docSize - 2);
              tr = tr.setSelection(Selection.near(tr.doc.resolve(safeFrom)));
              view.dispatch(tr);
            });
          },
          setDisabled: setDisabled, // 暴露禁用方法到 API
          isDisabled: isDisabled,   // 暴露状态查询方法到 API
          toggleDisabled: toggleDisabled, // 暴露切换方法到 API
        });
      }, 1000);

      // 监听字数统计事件
      const handleWordCount = (event) => {
        wordCount = event.detail;
      };
      
      window.addEventListener('milkdown-word-count', handleWordCount);
      
      // 清理事件监听器
      return () => {
        window.removeEventListener('milkdown-word-count', handleWordCount);
      };

    } catch (error) {
      console.error("Failed to create Crepe editor:", error);
      loading = false;
    }
  });

  onDestroy(() => {
    if (loading) return;
    if (crepeRef) {
      crepeRef.destroy();
    }
    setCrepeAPI({
      loaded: false,
      onShare: () => {},
      update: () => {},
    });
  });

  $: if (crepeRef && content) {
    console.log("Updating Crepe content:", content);
  }

  // 复制功能 - 使用独立的工具类
  export const copyAsText = async () => {
    if (!crepeRef) return false;
    const markdown = crepeRef.getMarkdown();
    return await copyTool.copyAsText(markdown);
  };

  export const copyAsHtml = async () => {
    if (!crepeRef) return false;
    const markdown = crepeRef.getMarkdown();
    return await copyTool.copyAsHtml(markdown);
  };

  export const copyAsOffice = async () => {
    if (!crepeRef) return false;
    const markdown = crepeRef.getMarkdown();
    return await copyTool.copyAsOffice(markdown);
  };

  export const copyAsMarkdown = async () => {
    if (!crepeRef) return false;
    const markdown = crepeRef.getMarkdown();
    return await copyTool.copyAsMarkdown(markdown);
  };

  // 新增：手动禁用/启用编辑器的方法
  export const setDisabled = (isDisabled) => {
    disabled = isDisabled;
    if (crepeRef && crepeRef.editor) {
      crepeRef.editor.action((ctx) => {
        const view = ctx.get(editorViewCtx);
        view.setProps({
          editable: () => !isDisabled,
        });
      });
    }
  };

  // 新增：获取当前禁用状态
  export const isDisabled = () => {
    return disabled;
  };

  // 新增：切换编辑器状态
  export const toggleDisabled = () => {
    setDisabled(!disabled);
  };

  // 响应式更新禁用状态
  $: if (crepeRef && crepeRef.editor) {
    crepeRef.editor.action((ctx) => {
      const view = ctx.get(editorViewCtx);
      view.setProps({
        editable: () => !disabled,
      });
    });
  }
</script>

<div class="editor-container" class:disabled>
  <div class="crepe flex h-full flex-1 flex-col" bind:this={divRef}></div>
  
  <!-- 禁用状态指示器 -->
  <!-- {#if disabled}
    <div class="disabled-overlay">
      <div class="disabled-message">
        <span class="disabled-icon">🔒</span>
        <span>编辑器已禁用</span>
      </div>
    </div>
  {/if} -->
  
  <!-- 字数统计显示 -->
  <!-- <div class="editor-stats">
    <span class="stat-item">字数: {wordCount.words}</span>
    <span class="stat-item">字符: {wordCount.characters}</span>
    <span class="stat-item">AI 改写: 选中文本后自动显示</span>
  </div> -->
</div>

<style>
  :global(.milkdown) {
    /* Font Families */
    --crepe-font-title: inherit;
    --crepe-font-default: inherit;
    --crepe-font-code: inherit;
  }
  :global(.milkdown) {
    min-height: 400px;
  }

  :global(.milkdown .editor) {
    outline: none;
  }

  :global(.milkdown .ProseMirror) {
    outline: none;
    min-height: 300px;
    padding: 0px;
  }
  :global(.milkdown .ProseMirror h1) {
    margin-top: 11px;
    margin-bottom: 11px;
  }
  :global(.milkdown .ProseMirror h2) {
    margin-top: 9px;
    margin-bottom: 9px;
  }
  :global(.milkdown .ProseMirror h3) {
    margin-top: 7px;
    margin-bottom: 7px;
  }
  :global(.milkdown .ProseMirror h4) {
    margin-top: 6px;
    margin-bottom: 6px;
  }
  :global(.milkdown .ProseMirror h5) {
    margin-top: 4px;
    margin-bottom: 4px;
  }
  :global(.milkdown .ProseMirror h6) {
    margin-top: 2px;
    margin-bottom: 2px;
  }

  .editor-container {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .editor-container {
    position: relative;
  }

  .editor-container.disabled {
    opacity: 0.6;
    pointer-events: none;
  }

  .disabled-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 100;
  }

  .disabled-message {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 20px;
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    color: #6c757d;
    font-size: 14px;
    font-weight: 500;
  }

  .disabled-icon {
    font-size: 16px;
  }

  .editor-stats {
    display: flex;
    gap: 16px;
    padding: 8px 12px;
    background: #f6f8fa;
    border-top: 1px solid #d0d7de;
    font-size: 12px;
    color: #656d76;
  }

  .stat-item {
    display: flex;
    align-items: center;
  }

  :global(.milkdown-highlight-keyword) {
    background-color: #fff3cd;
    border: 1px solid #ffeaa7;
    border-radius: 3px;
    padding: 1px 2px;
  }

  /* 豆包 AI 改写样式 - 完全按照图片 */
  :global(.douban-ai-rewrite) {
    width: 320px;
    background: #ffffff;
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
    padding: 20px;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', sans-serif;
  }

  :global(.douban-header) {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 4px;
  }

  :global(.douban-icon) {
    width: 20px;
    height: 20px;
    background: linear-gradient(135deg, #4f8cff 0%, #6eb6ff 100%);
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    color: white;
  }

  :global(.douban-title) {
    font-size: 16px;
    font-weight: 500;
    color: #1a1a1a;
    line-height: 1.2;
  }

  :global(.douban-subtitle) {
    font-size: 14px;
    color: #8a8a8a;
    margin-bottom: 16px;
    line-height: 1.4;
  }

  :global(.douban-input-section) {
    margin-bottom: 16px;
  }

  :global(.douban-input-wrapper) {
    position: relative;
    width: 100%;
  }

  :global(.douban-input) {
    width: 100%;
    height: 40px;
    padding: 0 44px 0 12px;
    border: 1.5px solid #e6e6e6;
    border-radius: 8px;
    font-size: 14px;
    color: #1a1a1a;
    background: #fafafa;
    transition: all 0.2s ease;
    box-sizing: border-box;
    outline: none;
  }

  :global(.douban-input:focus) {
    border-color: #4f8cff;
    background: #ffffff;
    box-shadow: 0 0 0 2px rgba(79, 140, 255, 0.1);
  }

  :global(.douban-input::placeholder) {
    color: #bfbfbf;
    font-size: 14px;
  }

  :global(.douban-send-btn) {
    position: absolute;
    right: 4px;
    top: 50%;
    transform: translateY(-50%);
    width: 32px;
    height: 32px;
    background: #4f8cff;
    border: none;
    border-radius: 6px;
    color: white;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
  }

  :global(.douban-send-btn:hover) {
    background: #3d7ce6;
    transform: translateY(-50%) scale(1.02);
  }

  :global(.douban-actions) {
    display: flex;
    flex-direction: column;
    gap: 0;
  }

  :global(.douban-action) {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 8px;
    border-radius: 6px;
    cursor: pointer;
    font-size: 14px;
    color: #1a1a1a;
    transition: background-color 0.15s ease;
    position: relative;
    min-height: 20px;
  }

  :global(.douban-action:hover) {
    background: #f5f5f5;
  }

  :global(.action-icon) {
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
  }

  :global(.action-arrow) {
    margin-left: auto;
    font-size: 16px;
    color: #bfbfbf;
    font-weight: 300;
  }

  :global(.tone-submenu) {
    margin-top: 8px;
    padding: 12px;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px solid #e9ecef;
  }

  :global(.tone-title) {
    font-size: 14px;
    font-weight: 500;
    color: #1a1a1a;
    margin-bottom: 8px;
  }

  :global(.tone-options) {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 6px;
  }

  :global(.tone-option) {
    padding: 8px 12px;
    background: white;
    border: 1px solid #e6e6e6;
    border-radius: 6px;
    text-align: center;
    font-size: 13px;
    color: #1a1a1a;
    cursor: pointer;
    transition: all 0.15s ease;
  }

  :global(.tone-option:hover) {
    background: #4f8cff;
    color: white;
    border-color: #4f8cff;
  }

  :global(.douban-result) {
    margin-top: 16px;
    padding: 16px;
    background: #f0f9ff;
    border-radius: 8px;
    border: 1px solid #bae6fd;
  }

  :global(.result-header) {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
  }

  :global(.result-header > span) {
    font-size: 14px;
    font-weight: 500;
    color: #0c4a6e;
  }

  :global(.result-actions) {
    display: flex;
    gap: 6px;
  }

  :global(.result-btn) {
    padding: 4px 8px;
    border: 1px solid #bae6fd;
    border-radius: 4px;
    background: white;
    font-size: 12px;
    cursor: pointer;
    transition: all 0.15s ease;
  }

  :global(.result-btn.accept) {
    background: #10b981;
    color: white;
    border-color: #10b981;
  }

  :global(.result-btn.accept:hover) {
    background: #059669;
  }

  :global(.result-btn:hover) {
    background: #f8fafc;
  }

  :global(.result-content) {
    font-size: 14px;
    line-height: 1.6;
    color: #1a1a1a;
    background: white;
    padding: 12px;
    border-radius: 6px;
    border: 1px solid #bae6fd;
  }

  :global(.douban-loading) {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 20px;
    color: #8a8a8a;
    font-size: 14px;
  }

  :global(.loading-dots) {
    width: 20px;
    height: 20px;
    border: 2px solid #f0f0f0;
    border-top: 2px solid #4f8cff;
    border-radius: 50%;
    animation: douban-loading-spin 1s linear infinite;
  }

  @keyframes douban-loading-spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
</style>
